﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LiveResults.Model
{
    public class Event
    {
        public delegate void ClassChangedHandler(EventClass cl);
        public event ClassChangedHandler ClassChanged;

        public delegate void RunnerChangedHandler(Runner r);
        public event RunnerChangedHandler RunnerChanged;

        public void FireRunnerChanged(Runner r)
        {
            RunnerChangedHandler h = RunnerChanged;
            if (h != null)
                h(r);
        }

        public void FireClassChanged(EventClass cl)
        {
            ClassChangedHandler h = ClassChanged;
            if (h != null)
                h(cl);
        }

        public Event()
        {
            Classes = new Dictionary<string, EventClass>();
        }

        public Dictionary<string, EventClass> Classes { get; set; }

        public void MergeAndUpdate(EventClass cl)
        {
            if (!Classes.ContainsKey(cl.ClassName))
            {
                Classes.Add(cl.ClassName, cl);
                FireClassChanged(cl);

                foreach (Runner r in cl.Runners.Values)
                {
                    FireRunnerChanged(r);
                }
            }
            else
            {
                if (!Classes[cl.ClassName].DefinitionEquals(cl))
                {
                    //Something changed, update and FireChange...
                    Classes[cl.ClassName].CourseLength = cl.CourseLength;
                    Classes[cl.ClassName].Order = cl.Order;
                    Classes[cl.ClassName].RadioControls = cl.RadioControls;
                    FireClassChanged(Classes[cl.ClassName]);
                }

                /*Merge Runners and find Changes*/
                List<Runner> deletedRunners;
                List<Runner> updatedRunners = Classes[cl.ClassName].UpdateRunnersInClassAndGetChanges(cl.Runners, out deletedRunners);

            }
        }
    }
}
